package com.server.server;

import com.server.constant.CommonConstant;
import com.server.exception.BusinessException;
import com.server.model.enums.ExceptionInfo;
import com.server.server.initializer.UdpShakeHandServerInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * Description: This is a sample class.
 * @Author Simon
 */
@Slf4j
public class UdpNettyServer {

    private static EventLoopGroup group;
    private static Bootstrap bootstrap;
    private static UdpShakeHandServerInitializer udpShakeHandServerInitializer;

    public static void start(){
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        udpShakeHandServerInitializer=new UdpShakeHandServerInitializer();
        try {
            bootstrap.group(group)
                    // todo 这几个参数之后需要优化
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(udpShakeHandServerInitializer);

            ChannelFuture f = bootstrap.bind(CommonConstant.UDP_LISTEN_PORT).sync();

            startConnect();

            f.channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void startConnect(){
        log.info("开启与服务端的安全信道建立过程");
        try {
            ChannelFuture channelFuture = bootstrap.connect(CommonConstant.AUTH_NEXUS_IP,
                    CommonConstant.AUTH_NEXUS_UDP_PORT).sync();
            channelFuture.addListener((ChannelFutureListener)arg -> {
                if (channelFuture.isSuccess()){
                    System.out.println("success");
                    log.info("authNexus服务器连接成功");
                }else{
                    System.out.println("failed");
                    log.info("服务器连接失败");
                    throw new BusinessException(ExceptionInfo.CONNECT_TO_AUTH_FAILED);
                }
            });

            ByteBuf requestMessage = Unpooled.copiedBuffer("test".getBytes());

            channelFuture.channel().writeAndFlush(requestMessage);

        } catch (InterruptedException e) {
            throw new BusinessException(ExceptionInfo.CONNECT_TO_AUTH_FAILED);
        }
    }
}
